<template>
  <div>


    <el-form :inline="true" top="10px" :model="userInfo" class="demo-form-inline">
      <el-form-item label="websocket">
        <el-input v-model="userInfo.websocketAddress" placeholder="websocket 地址"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="connectWs">连接服务</el-button>
      </el-form-item>

    </el-form>
    <vue-json-editor
      v-model="jsonData"
      :showBtns="false"
      :mode="'code'"
      lang="zh"
      @json-change="onJsonChange"
      @json-save="onJsonSave"
    />
    <el-button type="success" @click="send" plain>发送消息</el-button>
  </div>
</template>

<script>

  import vueJsonEditor from 'vue-json-editor'

  export default {
    name: "WebsocketTest",
    data() {
      return {
        editor: null,
        jsonData: {
          "key": "test:test",
          "content": {
            "name": "name",
            "dd": "aaa"
          }
        },
        path: '',
        socket: "",
        userInfo: {
          websocketAddress: 'ws://127.0.0.1:46000/ws'
        }
      };
    },
    components: {
      vueJsonEditor
    },

    methods: {

      connectWs() {
        this.init();
      },

      onJsonChange(value) {
        console.log('value:', value);
      },
      onJsonSave(value) {
        console.log('value:', value);
      },
      init() {
        if (typeof (WebSocket) === "undefined") {
          alert("您的浏览器不支持socket")
        } else {
          // 实例化socket
          this.socket = new WebSocket(this.userInfo.websocketAddress);
          // 监听socket连接
          this.socket.onopen = this.open;
          // 监听socket错误信息
          this.socket.onerror = this.error;
          // 监听socket消息
          this.socket.onmessage = this.getMessage;
          // 心跳包
          this.sendHeart();
        }
      },
      sendHeart: function () {
        var socket = this.socket;
        setInterval(function () {
          socket.send("");
          console.log("发送心跳")
        }, 2000)
      },
      open: function () {
        console.log("socket连接成功")
      },
      error: function () {
        console.log("连接错误")
      },
      getMessage: function (msg) {
        this.$message({
          message: '收到信息: ' + msg,
          type: 'success'
        });
      },
      send: function () {
        this.socket.send(JSON.stringify(this.jsonData));
        this.$message({
          message: "发送成功",
          type: 'success'
        });
      },
      close: function () {
        console.log("socket已经关闭")
      }
    },
    destroyed() {
      // 销毁监听
      this.socket.onclose = this.close
    }

    // catchData是一个类似回调函数，来自父组件，当然也可以自己写一个函数，主要是用来获取富文本编辑器中的html内容用来传递给服务端
  }
  ;
  // 创建富文本实例

</script>

<style scoped>

  /* jsoneditor右上角默认有一个链接,加css去掉了 */
  .jsoneditor-poweredBy {
    display: none;
  }

  .jsoneditor {

    height: 400px;
  }

</style>
